package com.luoying.itew.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.luoying.itew.R;
import com.luoying.itew.adapter.PhotoAdapter;
import com.luoying.itew.bean.SubmitLogPBean;
import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.event.SubmitLogSuccessEvent;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.GifSizeFilter;
import com.luoying.itew.util.Glide4Engine;
import com.luoying.itew.util.LogUtils;
import com.luoying.itew.util.ZXWUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lufan on 2019-06-17
 * Class describe 提交反馈图片
 */
public class SubmitPhotoActivity extends BaseActivity implements PhotoAdapter.AdapterListener{
    private static final String TAG = "SubmitPhotoActivity";
    /**
     * 选择图片请求码
     */
    public final int REQUEST_CODE_CHOOSE = 2001;

    @BindView(R.id.et_submit_log)
    EditText etSubmitLog;
    @BindView(R.id.recycleview_submit)
    RecyclerView recycleviewSubmit;
    @BindView(R.id.btn_submit_feedback)
    Button btnSubmitFeedback;

    private List<String> pathList = new ArrayList<>();
    private List<Uri> uriList = new ArrayList<>();
    private PhotoAdapter adapter;

    private String[] permissionStr = new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    public int getLayoutResId() {
        return R.layout.activity_submit_photo;
    }

    @Override
    protected void init() {
        super.init();
        adapter = new PhotoAdapter(this,pathList,uriList);
        recycleviewSubmit.setLayoutManager(new GridLayoutManager(this,3));
        recycleviewSubmit.setAdapter(adapter);
        adapter.setListener(this);
    }

    @Override
    protected void setSystemColor() {
        super.setSystemColor();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //点击back键finish当前activity
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    /**
     * 提交意见反馈请求
     */
    public void sendPostRequest(){
        if(TextUtils.isEmpty(etSubmitLog.getText().toString())){
            Toast.makeText(this,"未填写巡查内容",Toast.LENGTH_SHORT).show();
            return;
        }

        SubmitLogPBean bean = (SubmitLogPBean) this.getIntent().getSerializableExtra("bean");
        bean.setImgLog(new SubmitLogPBean.ImgLogBean(getPhotoValue()));
        bean.logContent = etSubmitLog.getText().toString();
        String json = new Gson().toJson(bean);
        int userId = UserManage.getInstance().getUserInfo().getUserId();
        loadDialog.show();
        HttpRequestUtils.getInstance().postLog(AntaiApplication.cuurMonitorId + "",
                userId + "", json, new HttpResponseCallBack<String>() {
                    @Override
                    public void onFail(String message) {
                        loadDialog.dismiss();
                        Toast.makeText(SubmitPhotoActivity.this, "反馈失败", Toast.LENGTH_SHORT).show();
                        LogUtils.d(TAG, "onFail " + message);
                    }

                    @Override
                    public void onSuccess(String data) {
                        loadDialog.dismiss();
                        EventBus.getDefault().post(new SubmitLogSuccessEvent());
                        Toast.makeText(SubmitPhotoActivity.this, "反馈成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new SubmitLogSuccessEvent());
                        SubmitLogActivity.mFinish.finish();
                        SignInActivity.mFinish.finish();
                        SubmitPhotoActivity.this.finish();
                    }

                    @Override
                    public void onError(String message) {
                        loadDialog.dismiss();
                        Toast.makeText(SubmitPhotoActivity.this, "反馈失败", Toast.LENGTH_SHORT).show();
                        LogUtils.d(TAG, "onError " + message);
                    }

                });
    }


    private List<String> getPhotoValue() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < uriList.size(); i++) {
            Bitmap bitmap = ZXWUtils.decodeUriAsBitmap(uriList.get(i),this);
            String base64 = ZXWUtils.bitmapToBase64(ZXWUtils.compressScale(bitmap));  //尺寸压缩图片并转为Base64
            list.add("data:image/png;base64," + base64);
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE_CHOOSE){
            if(resultCode==RESULT_OK){
                int count = Matisse.obtainPathResult(data).size();
                if((pathList.size()+count)>PhotoAdapter.MAX_SELECT){
                    Toast.makeText(this,"最多只能选择"+PhotoAdapter.MAX_SELECT+"个文件",Toast.LENGTH_SHORT).show();
                    int diff = (pathList.size()+count)- PhotoAdapter.MAX_SELECT;
                    pathList.addAll(Matisse.obtainPathResult(data).subList(0,count-diff));
                    uriList.addAll(Matisse.obtainResult(data).subList(0,count-diff));
                } else {
                    pathList.addAll(Matisse.obtainPathResult(data));
                    uriList.addAll(Matisse.obtainResult(data));
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    @OnClick(R.id.btn_submit_feedback)
    public void onViewClicked(View v) {
        sendPostRequest();
    }


    @Override
    public void onAddImage() {
        Matisse.from(SubmitPhotoActivity.this)
                .choose(MimeType.ofImage(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "com.luoying.itew.fileprovider","test"))
                .maxSelectable(PhotoAdapter.MAX_SELECT)
                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())// for glide-V4
                .originalEnable(true)
                .maxOriginalSize(10)
                .autoHideToolbarOnSingleTap(true)
                .forResult(REQUEST_CODE_CHOOSE);
//        SubmitPhotoActivityPermissionsDispatcher
    }

    @Override
    public void onDeleteClick(int index) {
        if(index<uriList.size()){
            uriList.remove(index);
            pathList.remove(index);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onImageClick(int index) {
        Intent intent = new Intent(this,PhotoPreviewActivity.class);
        intent.putExtra("img_uri",uriList.get(index));
        intent.putExtra("from",0);
        startActivity(intent);
    }

//    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA})
//    void onNeedsPermission() {
//        Matisse.from(SubmitPhotoActivity.this)
//                .choose(MimeType.ofImage(), false)
//                .countable(true)
//                .capture(true)
//                .captureStrategy(new CaptureStrategy(true, "com.luoying.itew.fileprovider","test"))
//                .maxSelectable(PhotoAdapter.MAX_SELECT)
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new Glide4Engine())// for glide-V4
//                .originalEnable(true)
//                .maxOriginalSize(10)
//                .autoHideToolbarOnSingleTap(true)
//                .forResult(REQUEST_CODE_CHOOSE);
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        SubmitPhotoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
//    }
//
//    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA})
//    public void onNeverAskAgain() {
//        Toast.makeText(this,"无权限,无法上传图片",Toast.LENGTH_LONG).show();
//    }
//
//    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA})
//    public void onPermissionDenied() {
//        Toast.makeText(this,"无权限,无法上传图片",Toast.LENGTH_LONG).show();
//    }
}
